package cn.com.surker.material.service.impl;

import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.dto.main.MainDiscountQueryDTO;
import cn.com.surker.dto.main.MainDiscountUpdateDTO;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.material.dao.MainMaterialDao;
import cn.com.surker.material.dao.MainMaterialDiscountDao;
import cn.com.surker.material.dao.MainSupplierDao;
import cn.com.surker.material.entity.MainMaterial;
import cn.com.surker.material.entity.MainMaterialDiscount;
import cn.com.surker.material.service.MainMaterialDiscountService;
import cn.com.surker.oa.dao.OaSupplierDao;
import cn.com.surker.oa.entity.OaSupplier;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.model.CacheUser;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.vo.main.MainMaterialBillVO;
import cn.com.surker.vo.main.MainMaterialDiscountVO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.snaker.engine.SnakerException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MainMaterialDiscountServiceImpl extends ServiceImpl<MainMaterialDiscountDao, MainMaterialDiscount> implements MainMaterialDiscountService {

    @Resource
    private MainMaterialDiscountDao dao;
    @Resource
    private MainMaterialDao mainMaterialDao;
    @Resource
    private MainSupplierDao mainSupplierDao;
    @Resource
    private MainMaterialDiscountDao materialDiscountDao;
    @Resource
    private OaSupplierDao supplierDao;
    @Resource
    private DataSourceInfoDao dsDao;

    @Override
    public IPage<MainMaterialDiscountVO> pageData(MainDiscountQueryDTO dto) {
        PageHelper.offsetPage(dto.getOffsetSize(), dto.getLimit());
        IPage<MainMaterialDiscountVO> mainSupplierPage = dao.page(new Page<>(dto.getCurrSize(), dto.getLimit()), dto);
        /**分页插件**/
        if (ObjectUtil.isNotEmpty(mainSupplierPage)) {
            PageInfo pageInfo = new PageInfo(mainSupplierPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal())) mainSupplierPage.setTotal(pageInfo.getTotal());
        }
        return mainSupplierPage;
    }

    @Override
    public Boolean saveMainMaterialDiscount(MainDiscountUpdateDTO dto, CacheUser user) {
        MainMaterialDiscount mainMaterialDiscount = BeanUtil.copyProperties(dto, MainMaterialDiscount.class);
        if (StringUtils.isNull(mainMaterialDiscount.getOrgId()))
            throw new MessageCenterException("公司信息为空~！");
        if (StringUtils.isNull(mainMaterialDiscount.getMaterialId()))
            throw new MessageCenterException("扣重材料信息为空");
        if (StringUtils.isNull(mainMaterialDiscount.getSupplierId()))
            throw new MessageCenterException("供应商信息为空");
        QueryWrapper<MainMaterialDiscount> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("material_id", mainMaterialDiscount.getMaterialId());
        query.eq("org_id", mainMaterialDiscount.getOrgId());
        query.eq("supplier_id", mainMaterialDiscount.getSupplierId());
        List<MainMaterialDiscount> list = materialDiscountDao.selectList(query);
        if (list != null && list.size() > 0) {
            MainMaterialDiscount discount = list.get(0);
            discount.setUpdateTime(new Date());
            discount.setUpdator(user.getName());
            discount.setType(mainMaterialDiscount.getType());
            discount.setWeight(mainMaterialDiscount.getWeight());
            discount.setRate(mainMaterialDiscount.getRate());
            Integer code = materialDiscountDao.updateById(discount);
            if (code > 0)
                return true;
            else
                return false;
        }
        if(mainMaterialDiscount.getType().intValue() == 0){
            if(ObjectUtil.isEmpty(mainMaterialDiscount.getWeight()) || mainMaterialDiscount.getWeight().doubleValue() < 0){
                throw new SnakerException("固定重量输入错误，请检查数据！");
            }
        }else{
            if(ObjectUtil.isEmpty(mainMaterialDiscount.getRate()) || mainMaterialDiscount.getRate().doubleValue() < 0){
                throw new SnakerException("扣重比例输入错误，请检查数据！");
            }
        }
        mainMaterialDiscount.setStatus(0);
        mainMaterialDiscount.setCreateTime(new Date());
        mainMaterialDiscount.setCreator(user.getName());
        return save(mainMaterialDiscount);
    }


    @Override
    public Boolean updateMainMaterialDiscount(MainDiscountUpdateDTO dto, CacheUser user) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new SnakerException("标识不存在，请检查数据！");
        }
        MainMaterialDiscount mainMaterialDiscountn = dao.selectById(dto.getId());
        if (ObjectUtil.isEmpty(mainMaterialDiscountn)) {
            throw new SnakerException("当前供应商不存在，请重新处理！");
        }
        BeanUtil.copyProperties(dto, mainMaterialDiscountn);
        mainMaterialDiscountn.setUpdateTime(new Date());
        mainMaterialDiscountn.setUpdator(user.getName());
        return updateById(mainMaterialDiscountn);
    }


    @Override
    public Boolean updateStatusById(MainDiscountUpdateDTO dto, CacheUser user) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new SnakerException("标识不存在，请检查数据！");
        }
        MainMaterialDiscount mainMaterialDiscountn = dao.selectById(dto.getId());
        if (ObjectUtil.isEmpty(mainMaterialDiscountn)) {
            throw new SnakerException("当前供应商不存在，请重新处理！");
        }
        mainMaterialDiscountn.setStatus(dto.getStatus());
        mainMaterialDiscountn.setUpdateTime(new Date());
        mainMaterialDiscountn.setUpdator(user.getName());
        return updateById(mainMaterialDiscountn);
    }

    @Override
    public List<Map<String,Object>> getMaterialListByOrgId(String orgId, Long supplierId) {
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (StrUtil.isEmpty(orgId)) {
            return resultList;
        }
        QueryWrapper<MainMaterial> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isNull(orgId))
            queryWrapper.lambda().eq(MainMaterial::getOrgId, orgId);
        queryWrapper.eq("status", 0);
        if (!StringUtils.isNull(supplierId)) {
            queryWrapper.inSql("material_id", "select material_id from main_material_contract_price" +
                    " where status = 0 and supplier_id = " + supplierId + " and org_id = " + orgId + " GROUP BY material_id ");
        }

        List<MainMaterial> mainMaterials = mainMaterialDao.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(mainMaterials)) {
            mainMaterials.forEach(mainMaterial -> {
                Map<String,Object> map = CollUtil.newHashMap();
                map.put("id", mainMaterial.getMaterialId());
                map.put("name", mainMaterial.getNameNorms());
                resultList.add(map);
            });
        }
        return resultList;
    }

    @Override
    public List<Map<String,Object>> getSupplierListByOrgId(String orgId) {
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (StrUtil.isEmpty(orgId)) {
            return resultList;
        }
        QueryWrapper<OaSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.inSql("id", "select supplier_id from oa_supplier_org where status = 0 and org_id = " + orgId);
        List<OaSupplier> mainSuppliersList = supplierDao.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(mainSuppliersList)) {
            mainSuppliersList.forEach(mainMaterial -> {
                Map<String,Object> map = CollUtil.newHashMap();
                map.put("id", mainMaterial.getId());
                map.put("name", mainMaterial.getFullName());
                resultList.add(map);
            });
        }
        return resultList;
    }
    /**
     * 材料扣重设置 分页方法
     * @return
     */
    public IPage<MainMaterialDiscountVO> pageCloud(String searchVal, Long orgId, Long supplierId, Long materialId, Integer offset, Integer limit) {
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId, DataBaseEnum.MYSQL.getCode());
        if (ds == null)
            throw new MessageCenterException("数据源不存在");
        PageHelper.offsetPage(offset, limit);
        IPage<MainMaterialDiscountVO> iPage = materialDiscountDao.findCloudPage(new Page<>(offset, limit),
                ds.getCode(), searchVal, orgId, supplierId, materialId);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }
    /**
     * 云端保存
     * @param dto
     * @return
     */
    public RestResultDto saveCloud(MainDiscountUpdateDTO dto) {
        MainMaterialDiscount mainMaterialDiscount = BeanUtil.copyProperties(dto, MainMaterialDiscount.class);
        if (StringUtils.isNull(mainMaterialDiscount.getOrgId()))
            throw new MessageCenterException("公司信息为空~！");
        if (StringUtils.isNull(mainMaterialDiscount.getMaterialId()))
            throw new MessageCenterException("扣重材料信息为空");
        if (StringUtils.isNull(mainMaterialDiscount.getSupplierId()))
            throw new MessageCenterException("供应商信息为空");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(dto.getOrgId(), DataBaseEnum.MYSQL.getCode());
        if (ds == null)
            throw new MessageCenterException("数据源不存在");

        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        MainMaterialDiscount discount = materialDiscountDao.findExistDiscount(dto.getDbCode(), dto.getOrgId(), dto.getSupplierId(), dto.getMaterialId());
        Date nowDate = new Date();
        if (discount != null) {
            String sql = "update main_material_discount set material_id=?, supplier_id=?, weight=?, rate=?, " +
                    "type=?,status=?, remark=?, creator=?, create_time=?, updator=?, update_time=? where id = ?";
            Object[] obj = {dto.getMaterialId(), dto.getSupplierId(),dto.getWeight(),dto.getRate(),dto.getType(),
            dto.getStatus(),dto.getRemark(),dto.getCreator(), DateUtil.convertString(nowDate),dto.getUpdator(),
                    DateUtil.convertString(nowDate),discount.getId()};
            jdbcTemplate.update(sql, obj);
            mainMaterialDiscount.setId(discount.getId());
            mainMaterialDiscount.setUpdateTime(nowDate);
            materialDiscountDao.updateCloud(ds.getCode(), mainMaterialDiscount);
            return RestResultDto.success("更新成功");
        }
        String sql = "insert into main_material_discount (org_id, material_id, supplier_id, weight, rate, type,\n" +
                "status, remark, creator, create_time, updator, update_time)\n" +
                "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        Object[] obj = {dto.getOrgId(), dto.getMaterialId(), dto.getSupplierId(),dto.getWeight(),dto.getRate(),dto.getType(),
                dto.getStatus(),dto.getRemark(),dto.getCreator(), DateUtil.convertString(nowDate),dto.getUpdator(),
                DateUtil.convertString(nowDate)};
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, new String[]{"ID"});
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i + 1, obj[i]);
                }
                return ps;
            }
        }, keyHolder);
        Long taskId = keyHolder.getKey().longValue();
        if (taskId < 1) {
            throw new MessageCenterException("新增本地扣重错误");
        }
        mainMaterialDiscount.setId(taskId);
        Integer code = materialDiscountDao.saveCloud(ds.getCode(), mainMaterialDiscount);
        if (code > 0)
            return RestResultDto.success("保存成功", mainMaterialDiscount);
        throw new MessageCenterException("新增本地扣重错误");
    }

    /**
     * 云端更新
     * @param dto
     * @return
     */
    public RestResultDto updateCloud(MainDiscountUpdateDTO dto) {
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new SnakerException("标识不存在，请检查数据！");
        }

        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(dto.getOrgId(), DataBaseEnum.MYSQL.getCode());
        if (ds == null)
            throw new MessageCenterException("数据源不存在");
        MainMaterialDiscount materialDiscount = dao.findExistDiscount(ds.getCode(), dto.getOrgId(), dto.getSupplierId(), dto.getMaterialId());
        if (ObjectUtil.isEmpty(materialDiscount)) {
            throw new SnakerException("当前供应商不存在，请重新处理！");
        }
        Date nowDate = new Date();
        BeanUtil.copyProperties(dto, materialDiscount);
        String sql = "update main_material_discount set material_id=?, supplier_id=?, weight=?, rate=?, " +
                "type=?,status=?, remark=?, creator=?, create_time=?, updator=?, update_time=? where id = ?";
        Object[] obj = {dto.getMaterialId(), dto.getSupplierId(),dto.getWeight(),dto.getRate(),dto.getType(),
                dto.getStatus(),dto.getRemark(),materialDiscount.getCreator(), DateUtil.convertString(nowDate),dto.getUpdator(),
                DateUtil.convertString(nowDate),materialDiscount.getId()};

        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        jdbcTemplate.update(sql, obj);
        materialDiscount.setUpdateTime(nowDate);
        Integer code = materialDiscountDao.updateCloud(ds.getCode(), materialDiscount);
        if (code > 0)
            return RestResultDto.success("更新成功");
        return RestResultDto.fail("更新失败");
    }
}
